package com.wstuo.common.customForm.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.apache.log4j.Logger;
import com.wstuo.common.config.category.dto.CategoryDTO;
import com.wstuo.common.config.category.service.ICICategoryService;
import com.wstuo.common.customForm.dao.IFormCustomDAO;
import com.wstuo.common.customForm.dao.IFormCustomTabsDAO;
import com.wstuo.common.customForm.dto.FormCustomDTO;
import com.wstuo.common.customForm.dto.FormCustomQueryDTO;
import com.wstuo.common.customForm.dto.FormCustomTabsDTO;
import com.wstuo.common.customForm.dto.SimpleFileDTO;
import com.wstuo.common.customForm.entity.FormCustom;
import com.wstuo.common.customForm.entity.FormCustomTabs;
import com.wstuo.common.customForm.util.FormCustomUtil;
import com.wstuo.common.dto.PageDTO;
import com.wstuo.common.scheduledTask.service.IScheduledTaskService;
import com.wstuo.common.security.utils.AppConfigUtils;
import com.wstuo.common.security.utils.AppContext;
import com.wstuo.common.tools.service.IExportInfoService;
import com.wstuo.common.util.MathUtils;

/**
 * 自定义表单模块Service层
 * 
 * @author Wstuo
 * 
 */
public class FormCustomService implements IFormCustomService {

	final static Logger LOGGER = Logger.getLogger(FormCustomService.class);

	@Autowired
	private IFormCustomDAO formCustomDAO;
	@Autowired
	private IScheduledTaskService scheduledTaskService;
	@Autowired
    private ICICategoryService cicategoryService;
	@Autowired
	private IFormCustomTabsDAO formCustomTabsDAO;
	@Autowired
	private IExportInfoService exportInfoService;
	@Autowired
	private AppContext appctx;
	/**
	 * 修改其他存在默认的选项
	 * @param dto 
	 * @param entity
	 */
	private void updateIsDefault(Boolean isDefault) {
		if (isDefault) {
			List<FormCustom> lis = formCustomDAO.findBy("isDefault", true);
			for (FormCustom fc : lis) {
				fc.setIsDefault(false);
			}
		}
	}
	@Transactional
	public Long saveFormCustom(FormCustomDTO dto) {
		FormCustom formCustom = new FormCustom();
		updateIsDefault(dto.getIsDefault());
		FormCustomDTO.dto2entity(dto, formCustom);
		if(dto.getCiCategoryNo()!=null){
			formCustom.setCiCategoryNo(dto.getCiCategoryNo());
		}
		if(dto.getTabsIds()!=null){
			List<FormCustomTabs> list = formCustomTabsDAO.findByIds(dto.getTabsIds());
			formCustom.setFormCustomTabs(list);
		}
		formCustom=formCustomDAO.merge(formCustom);
		return formCustom.getFormCustomId();
	}
	/**
	 * 查询默认的表单编号
	 * @return
	 */
	@Transactional
	public FormCustomDTO findIsDefault(String type) {
		FormCustomDTO customDTO=null;
		List<FormCustom> lis = formCustomDAO.findBy("isDefault", true);
		if(lis!=null && lis.size()>0){
			for (FormCustom formCustom : lis) {
				if(formCustom != null && type.equals(formCustom.getType())){
					customDTO =new FormCustomDTO();
					FormCustomDTO.entity2dto(formCustom, customDTO);
					entity2dto(formCustom, customDTO);
				}
			}
		}
		return customDTO;
	}

	@Transactional
	public void deleteFormCustom(Long[] formCustomIds) {
		List<FormCustom> form=formCustomDAO.findByIds(formCustomIds);
		List<FormCustom> list=new ArrayList<FormCustom>();
		for (FormCustom formCustom : form) {
			formCustom.setDataFlag((byte) 99);
			list.add(formCustom);
		}
		if(list.size()>0)
			formCustomDAO.mergeAll(list);
	}

	@Transactional
	public void updateFormCustom(FormCustomDTO dto) {
		FormCustom formCustom = new FormCustom();
		updateIsDefault(dto.getIsDefault());
		FormCustomDTO.dto2entity(dto, formCustom);
		if(dto.getCiCategoryNo()!=null){
			formCustom.setCiCategoryNo(dto.getCiCategoryNo());
		}
		formCustomDAO.merge(formCustom);
	}

	@SuppressWarnings("unchecked")
	@Transactional
	public PageDTO findFormCustomPager(FormCustomQueryDTO queryDto,
			String sord, String sidx) {
		PageDTO p = formCustomDAO.findPager(queryDto, sord, sidx);
		List<FormCustom> formCustoms = p.getData();
		List<FormCustomQueryDTO> dtos = new ArrayList<FormCustomQueryDTO>();
		for (FormCustom formCustom : formCustoms) {
			FormCustomQueryDTO dto = new FormCustomQueryDTO();
			FormCustomQueryDTO.entity2dto(formCustom, dto);
			if(formCustom.getCiCategoryNo()!=null && formCustom.getCiCategoryNo()!=0){
				dto.setCiCategoryNo(formCustom.getCiCategoryNo());
				CategoryDTO categoryDTO=cicategoryService.findCICategoryById(formCustom.getCiCategoryNo());
				dto.setCiCategoryName(categoryDTO.getCname());
			}
			entity2queryDto(formCustom, dto);
			dtos.add(dto);
		}
		p.setData(dtos);
		return p;
	}

	@Transactional
	public FormCustomDTO findFormCustomByServiceDirId(
			FormCustomQueryDTO queryDto) {
		FormCustom formCustom = formCustomDAO.findFormCustom(queryDto);
		FormCustomDTO dto = new FormCustomDTO();
		if(formCustom!=null){
			FormCustomDTO.entity2dto(formCustom, dto);
		}
		return dto;
	}

	@Transactional
	public FormCustomQueryDTO findFormCustomById(Long formCustomId) {
		FormCustom formCustom = formCustomDAO.findById(formCustomId);
		FormCustomQueryDTO dto = new FormCustomQueryDTO();
		if(formCustom!=null){
			FormCustomQueryDTO.entity2dto(formCustom, dto);
			if(formCustom.getCiCategoryNo()!=null && formCustom.getCiCategoryNo()!=0){
				dto.setCiCategoryNo(formCustom.getCiCategoryNo());
				CategoryDTO categoryDTO=cicategoryService.findCICategoryById(formCustom.getCiCategoryNo());
				dto.setCiCategoryName(categoryDTO.getCname());
			}
			entity2queryDto(formCustom, dto);
		}
		return dto;
	}

	@Transactional
	public List<FormCustomQueryDTO> findSimilarFormCustom(FormCustomQueryDTO queryDto) {
		List<FormCustom> formCustoms = formCustomDAO
				.findSimilarFormCustom(queryDto);
		List<FormCustomQueryDTO> dtos = new ArrayList<FormCustomQueryDTO>();
		for (FormCustom formCustom : formCustoms) {
			if(formCustom!=null){
				FormCustomQueryDTO dto = new FormCustomQueryDTO();
				FormCustomQueryDTO.entity2dto(formCustom, dto);
				dtos.add(dto);
			}
		}
		return dtos;
	}
	
	@Transactional
	public List<FormCustomQueryDTO> findAllFormCustom(){
		List<FormCustom> formCustoms = formCustomDAO.findAll();
		List<FormCustomQueryDTO> dtos = new ArrayList<FormCustomQueryDTO>();
		for (FormCustom formCustom : formCustoms) {
			if(formCustom!=null){
				FormCustomQueryDTO dto = new FormCustomQueryDTO();
				FormCustomQueryDTO.entity2dto(formCustom, dto);
				dtos.add(dto);
			}
		}
		return dtos;
	}
	
	@Transactional
	public List<FormCustomQueryDTO> findAllRequestFormCustom(){
		FormCustomQueryDTO queryDto = new FormCustomQueryDTO();
		queryDto.setType("request");
		List<FormCustom> formCustoms = formCustomDAO.findSimilarFormCustom(queryDto);
		List<FormCustomQueryDTO> dtos = new ArrayList<FormCustomQueryDTO>();
		for (FormCustom formCustom : formCustoms) {
			if(formCustom!=null){
				FormCustomQueryDTO dto = new FormCustomQueryDTO();
				FormCustomQueryDTO.entity2dto(formCustom, dto);
				dtos.add(dto);
			}
		}
		return dtos;
	}
	
	
	@Transactional
	public FormCustomDTO findFormCustomByCiCategoryNo(Long ciCategoryNo) {
		FormCustomDTO customDTO=null;
		/*List<FormCustom> formCustoms=formCustomDAO.findBy("ciCategoryNo", ciCategoryNo);
		if(formCustoms!=null&&formCustoms.size()>0){
			customDTO =new FormCustomDTO();
			FormCustom formCustom = formCustoms.get(0);
			FormCustomDTO.entity2dto(formCustom, customDTO);
			entity2dto(formCustom, customDTO);
		}*/
		FormCustom formCustom=formCustomDAO.findUniqueBy("ciCategoryNo", ciCategoryNo);
		if(formCustom != null){
			customDTO =new FormCustomDTO();
			FormCustomDTO.entity2dto(formCustom, customDTO);
			entity2dto(formCustom, customDTO);
		}
		return customDTO;
	}
	
	private void entity2queryDto(FormCustom formCustom ,FormCustomQueryDTO customDTO){
		if(formCustom.getFormCustomTabs()!=null && formCustom.getFormCustomTabs().size()>0){
			List<FormCustomTabsDTO> formCustomTabsDtos = new ArrayList<FormCustomTabsDTO>();
			for (FormCustomTabs formCustomTabs : formCustom.getFormCustomTabs()) {
				FormCustomTabsDTO tabDto = new FormCustomTabsDTO();
				FormCustomTabsDTO.entity2dto(formCustomTabs, tabDto);
				formCustomTabsDtos.add(tabDto);
			}
			customDTO.setFormCustomTabsDtos(formCustomTabsDtos);
		}
	}
	/**
	 * entity to dto
	 * @param formCustom
	 * @param customDTO
	 */
	private void entity2dto(FormCustom formCustom ,FormCustomDTO customDTO){
		if(formCustom.getFormCustomTabs()!=null && formCustom.getFormCustomTabs().size()>0){
			List<FormCustomTabsDTO> formCustomTabsDtos = new ArrayList<FormCustomTabsDTO>();
			for (FormCustomTabs formCustomTabs : formCustom.getFormCustomTabs()) {
				FormCustomTabsDTO tabDto = new FormCustomTabsDTO();
				FormCustomTabsDTO.entity2dto(formCustomTabs, tabDto);
				formCustomTabsDtos.add(tabDto);
			}
			customDTO.setFormCustomTabsDtos(formCustomTabsDtos);
		}
	}
	
	@Transactional
	public Boolean isFormCustomNameExisted(FormCustomQueryDTO dto){
		Boolean flag = formCustomDAO.isFormCustomNameExisted(dto);
		return flag;
	}
	
	@Transactional
	public Boolean isFormCustomNameExistedOnEdit(FormCustomQueryDTO dto){
		Boolean flag = false;
		FormCustom formCustom =null;
		if(dto.getFormCustomId()!=null){
			formCustom = formCustomDAO.findById(dto.getFormCustomId());
		}
		if (formCustom != null && formCustom.getFormCustomName().equals(dto.getFormCustomName())){
        	flag = true;
        }else{
        	flag = formCustomDAO.isFormCustomNameExisted(dto);
        }
		return flag;
	}
	/**
	 * 
	 */
	@Deprecated
	@Transactional
	public SimpleFileDTO generateTemplateWithCategory(Long categoryNo) {
		SimpleFileDTO fileDTO = new SimpleFileDTO();
		File file = null;
		String categoryName = cicategoryService.findCategoryNameIncludParent(null,categoryNo);
		FormCustom formCustom = formCustomDAO.findUniqueBy("ciCategoryNo", categoryNo);
		if( formCustom != null && MathUtils.isPositive( formCustom.getFormCustomId() ) ){ 
			String path = AppConfigUtils.getInstance().getConfigPathByTenantId(
					"exportFilePath", "exportFile", appctx.getCurrentTenantId());
			String filePath = path + File.separator + categoryName + IExportInfoService.FILE_EXTENSION;
			exportInfoService.exportCSV(filePath , generateExportData(formCustom) );
			file = new File(filePath);
		}else{//如果没有关联自定义表单的就使用默认的模板文件
			file = new File(getDefaultTemplate()+"/ConfigureItem.csv");
		}
   		try {
   			if( file != null && file.exists()){
   	   	   		fileDTO.setInputStream(new FileInputStream(file)) ;
   			}
		} catch (FileNotFoundException e) {
			LOGGER.error(e);//e.printStackTrace();
		}
		fileDTO.setFileName(categoryName,IExportInfoService.FILE_EXTENSION);
		return fileDTO;
	}
	/**
	 * 生成导出文件的表头字段
	 * @param formCustom
	 * @return
	 */
	private List<String[]> generateExportData( FormCustom formCustom ){
		Set<String> exSet = new HashSet<String>();//排除的字段
		exSet.add("ciDto.companyName");//因为公司名是导入的时候选的，所以不用这个
		Map<String, String> fixedCol = null;// new HashMap<String, String>();//添加固定字段导入
		//LanguageContent lc = LanguageContent.getInstance();
		//fixedCol.put(lc.getContent("label.customReport.ciStatus"), "status");//状态
		String[] data = FormCustomUtil.decodeFrom( formCustom.getFormCustomContents(),
				exSet,fixedCol,IExportInfoService.STRING_SEPARATOR );
		List<String[]> datas = new ArrayList<String[]>();
		if( data != null ){
			datas.add(data);
		}
		return datas;
	}
	/**
	 * 获取默认模板的位置
	 * @return
	 */
	private String getDefaultTemplate(){
   		//String path = this.getClass().getResource("/").getPath();//指向classes
		String path = AppConfigUtils.getInstance().getConfigPath("", "importFile/")+"/";
		String lang = appctx.getCurrentLanguage() ;
		lang = "zh_CN";
		return path + lang ;
	}
}
